<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="SpuParams.spuName"></el-input>
      </el-form-item>
      <el-form-item label="SPU品牌">
        <el-select style="width: 240px" v-model="SpuParams.tmId">
          <el-option
            v-for="(item) in AllTradMarks"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          placeholder="请输入SPU描述"
          v-model="SpuParams.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图标">
        <!-- v-model="file-list"->默认展示文件
             action:上传文件的接口地址
             list-type:文件列表类型（text：文本，picture:照片格式，picture-card：照片墙格式）
             on-preview：点击预览触发钩子
             on-remove:文件列表移除文件钩子
             -->
        <el-upload
          v-model:file-list="imgList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="handlerUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="dialogImageUrl"
            alt="Preview Image"
            style="width: 100%; height: 100%"
          />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性">
        <!-- 展示销售属性的下拉菜单 -->
        <el-select
          style="width: 240px"
          :placeholder="
            unSelectSaleAttr.length ? `还未选择${unSelectSaleAttr.length}个` : '无'
          "
          v-model="saleAttrIdAndValueName"
        >
          <el-option
            v-for="(item) in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          size="default"
          @click="addSaleAttr"
          icon="plus"
          style="margin-left: 10px"
          :disabled="saleAttrIdAndValueName ? false : true"
          >添加销售属性</el-button
        >
        <!-- 展示销售属性的table -->
        <el-table border style="margin: 10px 0px" :data="saleAttr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="销售属性名字"
            align="center"
            width="120px"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="销售属性值">
            <!-- row:已有销售属性对象 -->
            <template #="{ row}">
              <el-tag
                v-for="(item, index) in row.spuSaleAttrValueList"
                :key="row.id"
                closable
                style="margin: 10px 5px"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ item.saleAttrValueName }}
              </el-tag>
              <el-input
                @blur="toLook(row)"
                v-model="row.saleAttrValue"
                v-if="row.flag == true"
                placeholder="请输入属性值"
                size="small"
                clearable
                @change=""
                style="width: 100px"
              ></el-input>
              <el-button
                type="primary"
                size="small"
                @click="toEdit(row)"
                icon="plus"
                v-else
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <template #="{$index }">
              <el-button
                type="primary"
                size="small"
                @click="saleAttr.splice($index, 1)"
                icon="delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button
          :disabled="saleAttr.length > 0 ? false : true"
          type="primary"
          size="default"
          @click="save"
          >保存</el-button
        >
        <el-button type="primary" size="default" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {
  reqAllTradmark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from "@/api/product/spu";
import type {
  SaleAttrValue,
  SpuImg,
  AllTradMark,
  SpuData,
  SpuHasImg,
  baseSaleDateList,
  spuSaleAttrList,
  Tradmark,
  SaleDate,
  baseSaleDate,
} from "@/api/product/spu/type";
import { ElMessage } from "element-plus";
import { ref, computed } from "vue";
let $emit = defineEmits(["changeScene"]);
//存储已有spu数据
let AllTradMarks = ref<Tradmark[]>([]);
//存储img数据
let imgList = ref<SpuImg[]>([]);
//存储spu已有销售属性
let saleAttr = ref<SaleDate[]>([]);
//存储全部销售属性
let allSaleAttr = ref<baseSaleDate[]>([]);
//定义数组接收已有SPU
let SpuParams = ref<SpuData>({
  category3Id: "", //三级分类的id
  description: "", //spu的描述
  spuImageList: [],
  spuName: "", //spu的名字
  spuSaleAttrList: [],
  tmId: "", //品牌的ID,
});
//存储展示url地址
let dialogImageUrl = ref<string>("");

//收集还未选择的销售属性ID与名字
let saleAttrIdAndValueName = ref<string>("");

//标记控制
//子组件点击取消：通知父组件切换场景1，展示已有的SPU数据
const cancel = () => {
  $emit("changeScene", {flag:0,params:'updata'});
};
const initHasSpuData = async (spu: SpuData) => {
  //存储已有的SPU对象，将来在模板中展示
  SpuParams.value = spu;

  //spu：即为父组件传递过来的SPU对象【不完整】
  //获取全部品牌数据
  let result: AllTradMark = await reqAllTradmark();
  //获取品牌图片
  let resultimg: SpuHasImg = await reqSpuImageList(spu.id as number);
  //获取已有的SPU销售属性的数据
  let resultSale: spuSaleAttrList = await reqSpuHasSaleAttr(spu.id as number);
  //获取整个项目全部SPU的销售属性
  let resultBase: baseSaleDateList = await reqAllSaleAttr();
  //存储全部品牌数据
  AllTradMarks.value = result.data;
  //返回值与要求字段不一致，使用map进性处理
  saleAttr.value = resultSale.data;
  allSaleAttr.value = resultBase.data;
  imgList.value = resultimg.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
};

//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false);
//点击回调显示
let handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
//删除文件列表
const handleRemove = () => {};
//照片墙上传文件之前的钩子(约束文件类型和大小)
const handlerUpload = (file: any) => {
  if (file.type == "image/png" || file.type == "image/jpeg" || file.type == "image/gif") {
    if (file.size / 1024 / 1024 < 3) {
      ElMessage({
        type: "success",
        message: "上传成功",
      });
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "文件大小小于3M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "文件格式不符合要求",
    });
    return false;
  }
};
//计算当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  //全部销售属性：颜色，版本，尺码
  //已有的销售属性：颜色，版本
  let unSelectAttr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName;
    });
  });
  return unSelectAttr;
});
//添加属性的方法
const addSaleAttr = () => {
  let [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(":");
  // baseSaleAttrId: number, //必须
  //   saleAttrName: string,   //必须
  //   spuSaleAttrValueList: SaleAttrValue[],
  let newSaleArr: any = {
    baseSaleAttrId, //必须
    saleAttrName, //必须
    spuSaleAttrValueList: [],
  };
  //追加到数组当中
  saleAttr.value.push(newSaleArr);
  //添加完后清空
  saleAttrIdAndValueName.value = "";
};
//属性值按钮点击事件(点击切换编辑模式)
const toEdit = (row: SaleDate) => {
  row.flag = true;
  //动态追加字段
  row.saleAttrValue = "";
};
//
const toLook = (row: SaleDate) => {
  //整理收集到的属性ID与属性值的名字
  const { baseSaleAttrId, saleAttrValue } = row;
  //整理成服务器需要的属性值形式
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  };
  //非法情况判断
  if ((saleAttrValue as string).trim() == "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
  }
  //判断属性值是否在数组中存在
  let repate = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue;
  });
  if (repate) {
    ElMessage({
      type: "error",
      message: "属性值重复",
    });
    return;
  }
  //追加属性
  row.spuSaleAttrValueList.push(newSaleAttrValue);
  //切换为查看模式
  row.flag = false;
};
//保存按钮回调
const save = async () => {
  //整理收集到的参数
  //发请求：添加spu/修改spu
  //照片墙数据
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  console.log(SpuParams.value.spuImageList);
  //整理销售属性数据
  SpuParams.value.spuSaleAttrList = saleAttr.value;
  let sesult = await reqAddOrUpdateSpu(SpuParams.value);
  if (sesult.code == 200) {
    ElMessage({
      type: "success",
      message: SpuParams.value.id ? "更新成功" : "添加成功",
    });
    //flag:切换场景标识，params:修改更新标识符
    $emit("changeScene", {flag:0,params:SpuParams.value.id?'update':'add'});
  } else {
    ElMessage({
      type: "error",
      message: SpuParams.value.id ? "更新失败" : "添加失败",
    });
  }
};
//添加已个新的SPU的方法
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(SpuParams.value, {
    category3Id: "", //三级分类的id
    description: "", //spu的描述
    spuImageList: [],
    spuName: "", //spu的名字
    spuSaleAttrList: [],
    tmId: "", //品牌的ID,
    id:'',
  });
  //清空图片列表
  imgList.value = [];
  saleAttr.value = [];
  saleAttrIdAndValueName.value = '',
  //存储三级分类的Id
  SpuParams.value.category3Id = c3Id;
  //获取全部品牌数据
  let result: AllTradMark = await reqAllTradmark();
  //获取整个项目全部SPU的销售属性
  let resultBase: baseSaleDateList = await reqAllSaleAttr();
  //存储数据
  AllTradMarks.value = result.data;
  allSaleAttr.value = resultBase.data;
};
//给父组件暴露方法
defineExpose({ initHasSpuData, initAddSpu });
</script>

<style scoped></style>
